import OpenAI from "openai";
import "dotenv/config";

// AI生成题目接口
export async function aiGenerate(ctx) {
  const { type, lang, count } = ctx.request.body;
  const openai = new OpenAI({
    apiKey: process.env.ALI_API_KEY,
    baseURL: "https://dashscope.aliyuncs.com/compatible-mode/v1",
  });

  // 构造 prompt
  let prompt = '';
  if (type === '编程题') {
    prompt = `请帮我出${count || 2}道${lang || ''}相关的${type || ''}，以JSON数组格式返回，每个对象包含title, content，不需要answer和options字段。`;
  } else {
    prompt = `请帮我出${count || 2}道${lang || ''}相关的${type || ''}题目，以JSON数组格式返回，每个对象包含title, content, options(如有), answer(包含A，B，C，D四个选项）。请确保每道题都给出标准答案，answer字段为标准答案。`;
  }

  let questions = [];
  try {
    const completion = await openai.chat.completions.create({
      model: "qwen-plus",
      messages: [
        { role: "user", content: prompt },
      ],
    });
    const content = completion.choices[0].message.content;
    // 处理AI返回内容中可能的 markdown 代码块包裹和多余内容
    let jsonStr = content.trim();
    if (jsonStr.startsWith('```')) {
      jsonStr = jsonStr.replace(/^```[a-zA-Z]*\n?|```$/g, '').trim();
    }
    // 只保留第一个有效JSON数组，去除后续多余内容
    const match = jsonStr.match(/\[.*\]/s);
    if (match) {
      jsonStr = match[0];
    }
    questions = JSON.parse(jsonStr);
    // options 统一为数组，编程题无options/answer
    questions = questions.map(q => ({
      ...q,
      options: type === '编程题' ? [] : (q.options || []),
      answer: type === '编程题' ? '' : (q.answer || ''),
      type,
      lang,
    }));
    ctx.body = questions;
  } catch (e) {
    console.error("AI生成题目失败", e);
    ctx.status = 500;
    ctx.body = { msg: "AI返回格式解析失败", detail: e.message };
  }
}
